//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal sealed class ExternSheetRecord : WorkbookLevelRecord
    {
        private Xti[] _data;

        public ExternSheetRecord(BiffWriterWorkbookContext context, ExternalLink link)
        {
            _data = new Xti[context.Workbook.Sheets.Count];
            for (ushort i = 0; i < _data.Length; i++)
            {
                _data[i] = new Xti(0, i, i);
            }
        }

        public ExternSheetRecord()
        {
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.ExternSheet; }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            ushort count = (ushort) _data.Length;
            context.WriteUInt16(count);
            foreach (var xti in _data)
            {
                xti.Write(context.Writer);
            }
        }
        
        protected override void ReadContent(BiffReaderContext context, int length)
        {
             var count = context.ReadUInt16();
            _data = new Xti[count];
            for (int i = 0; i < count; i++)
            {
                Xti r = new Xti(context.ReadUInt16(), context.ReadUInt16(), context.ReadUInt16());
                _data[i] = r;
            }

        }

        public override void Apply(BiffReaderWorkbookContext context)
        {
            foreach (var xti in _data)
            {
                var workbook = context.ExternalBookContexts[xti.ExternalBookIndex].Workbook;
                //var workbook = context.Workbook.ExternalLinks[xti.ExternalBookIndex].ExternalBook;
                context.ExternalSheets.Add(new ExternalReferencedSheet(workbook, xti.FirstTabIndex, xti.LastTabIndex));
                
            }
        }



        struct Xti
        {
            public readonly ushort ExternalBookIndex;
            public readonly ushort FirstTabIndex;
            public readonly ushort LastTabIndex;

            public Xti(ushort externalBookIndex, ushort firstTabIndex, ushort lastTabIndex)
            {
                ExternalBookIndex = externalBookIndex;
                FirstTabIndex = firstTabIndex;
                LastTabIndex = lastTabIndex;
            }
            public override string ToString()
            {
                return string.Format("externalBookIndex{0} FirstTabIndex= {1} LastTabIndex = {2} ", ExternalBookIndex, FirstTabIndex, LastTabIndex);
            }

            public void Write(BinaryWriter writer)
            {
                writer.Write(ExternalBookIndex);
                writer.Write(FirstTabIndex);
                writer.Write(LastTabIndex);
            }
        }
    }
}